<!--
*Author：COCO
 *代码由框架生成,任何更改都可能导致被代码生成器覆盖
 *业务请在@/extension/custom/custom/Base_DefectItem.js此处编写
 -->
<template>
    <view-grid ref="grid"
               :columns="columns"
               :detail="detail"
               :editFormFields="editFormFields"
               :editFormOptions="editFormOptions"
               :searchFormFields="searchFormFields"
               :searchFormOptions="searchFormOptions"
               :table="table"
               :extend="extend"
               @show-details="showDetails">
    </view-grid>
    
    <!-- 添加内联的弹框组件作为备用 -->
    <el-dialog
      v-model="backupDialogVisible"
      :width="1100"
      title="生产工单详情"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      :z-index="9999"
    >
      <div>
        <!-- 基本信息卡片 -->
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <div style="display: flex; flex-wrap: wrap;">
            <div style="flex:1 0 300px;">工单状态：{{ currentDetailRow.WorkOrderStatus || '-' }}</div>
            <div style="flex:1 0 300px;">工单编号：{{ currentDetailRow.ProductionWorkOrderCode || '-' }}</div>
            <div style="flex:1 0 300px;">客户名称：祥顺有限公司</div>
            <div style="flex:1 0 300px;">生产编号：SC781431</div>
            
            <div style="flex:1 0 300px;">订单编号：DD6272041</div>
            <div style="flex:1 0 300px;">优先级：<span style="color: #ff6b00; font-weight: bold;">紧急</span></div>
            <div style="flex:1 0 300px;">备注：</div>
            
            <div style="flex:1 0 300px;">创建时间：{{ currentDetailRow.CreateDate || '-' }}</div>
            <div style="flex:1 0 300px;">创建人：{{ currentDetailRow.Creator || '-' }}</div>
            <div style="flex:1 0 300px;">最后更新时间：{{ currentDetailRow.CreateDate || '-' }}</div>
            
            <div style="flex:1 0 300px;">成品名称：保险柜</div>
            <div style="flex:1 0 300px;">成品编号：CP712049</div>
            <div style="flex:1 0 300px;">规格型号：规格一</div>
            <div style="flex:1 0 300px;">尺寸：尺寸一</div>
            
            <div style="flex:1 0 300px;">计划产量：30</div>
            <div style="flex:1 0 300px;">车间：{{ currentDetailRow.WorkshopId || '-' }}</div>
            <div style="flex:1 0 300px;">工艺路线：{{ currentDetailRow.ProcessmanagementId || '-' }}</div>
            
            <div style="flex:1 0 300px;">计划开始日期：2023-7-5 10:00</div>
            <div style="flex:1 0 300px;">计划结束日期：2023-7-6 15:00</div>
          </div>
        </el-card>
        
        <!-- 工序任务卡片 -->
        <el-card class="detail-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>工序任务</span>
            </div>
          </template>
          <el-table :data="currentDetailRow.WorkOrderList || []" style="width: 100%;">
            <el-table-column prop="WorkOrderCode" label="工序编号"/>
            <el-table-column prop="WorkOrderStatus" label="工序名称"/>
            <el-table-column prop="PlanStartDate" label="计划开始时间"/>
            <el-table-column prop="PlanEndDate" label="计划结束时间"/>
            <el-table-column prop="FinishNum" label="完成数量"/>
            <el-table-column prop="CurrentProcess" label="当前状态"/>
          </el-table>
        </el-card>
        
        <!-- 成品信息卡片 -->
        <el-card class="detail-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>成品信息</span>
            </div>
          </template>
          <el-table :data="currentDetailRow.OrderProductList || []" style="width: 100%;">
            <el-table-column prop="productCode" label="成品编号"/>
            <el-table-column prop="productName" label="成品名称"/>
            <el-table-column prop="productType" label="规格型号"/>
            <el-table-column prop="productBatch" label="批次号"/>
            <el-table-column prop="productCompany" label="成品单位">
              <template #default="scope">
                {{ getProductUnitText(scope.row.productCompany) }}
              </template>
            </el-table-column>
            <el-table-column prop="productState" label="成品状态">
              <template #default="scope">
                {{ getProductStateText(scope.row.productState) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="backupDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
</template>
<script>
    import extend from "@/extension/productmanage/productmanage/productworkorder.js";
    import { ref, defineComponent, onMounted } from "vue";
    import http from '@/api/http';
    
    // 在组件创建前就将showDetails方法传递给扩展对象
    let showDetailsFunction = null;
    if (extend && extend.methods) {
        extend.methods.showDetailsFromParent = function(row) {
            if (showDetailsFunction) {
                showDetailsFunction(row);
            } else {
                console.error('showDetailsFunction尚未初始化');
            }
        };
    }
    
    export default defineComponent({
        setup() {
            const detailsDialogVisible = ref(false);
            const backupDialogVisible = ref(false);
            const currentDetailRow = ref({
                ProductionWorkOrderId: '',
                ProductionWorkOrderCode: '',
                WorkOrderStatus: '',
                WorkOrderPriority: '',
                WorkshopId: '',
                ProcessmanagementId: '',
                Creator: '',
                CreateDate: '',
                OrderProductList: [],
                PlanList: [],
                WorkOrderList: []
            });
            const grid = ref(null);
            
            async function showDetails(row) {
                try {
                    // 重置状态
                    detailsDialogVisible.value = false;
                    backupDialogVisible.value = false;
                    currentDetailRow.value = {};
                    
                    console.log('调用详情方法，入参:', row);
                    
                    // 获取成品信息
                    let fetchedOrderProductList = [];
                    if (row.ProductionOrderId) {
                        try {
                            const response = await http.get(`/api/OrderProductList/GetOrderDetailsByIdAsync?productionOrderId=${row.ProductionOrderId}`, null, true);
                            fetchedOrderProductList = response;
                            console.log("获取到的成品信息:", response);
                        } catch (error) {
                            console.error('获取成品信息失败:', error);
                        }
                    }

                    // 设置当前行数据
                    currentDetailRow.value = {
                        ProductionWorkOrderId: row.ProductionWorkOrderId || '',
                        ProductionWorkOrderCode: row.ProductionWorkOrderCode || '',
                        WorkOrderStatus: row.WorkOrderStatus || '',
                        WorkOrderPriority: row.WorkOrderPriority || '',
                        WorkshopId: row.WorkshopId || '',
                        ProcessmanagementId: row.ProcessmanagementId || '',
                        Creator: row.Creator || '',
                        CreateDate: row.CreateDate || '',
                        OrderProductList: fetchedOrderProductList,
                        PlanList: [], // 如果有计划数据，可以在这里添加
                        WorkOrderList: [] // 如果有工单数据，可以在这里添加
                    };

                    console.log('设置详情数据:', currentDetailRow.value);
                    
                    // 显示弹框
                    console.log('弹框显示状态(修改前):', detailsDialogVisible.value);
                    
                    // 使用setTimeout确保DOM已更新
                    setTimeout(() => {
                        // 同时设置两个弹框，看哪个能正常显示
                        detailsDialogVisible.value = true;
                        backupDialogVisible.value = true;
                        console.log('弹框显示状态(修改后):', detailsDialogVisible.value);
                        console.log('备用弹框显示状态(修改后):', backupDialogVisible.value);
                        
                        // 添加延迟检查
                        setTimeout(() => {
                            console.log('弹框显示状态(延迟检查):', detailsDialogVisible.value);
                            console.log('备用弹框显示状态(延迟检查):', backupDialogVisible.value);
                            console.log('currentDetailRow:', currentDetailRow.value);
                        }, 100);
                    }, 0);
                } catch (error) {
                    console.error('显示详情时出错:', error);
                }
            }
            
            // 将showDetails函数保存到全局变量中
            showDetailsFunction = showDetails;
            
            onMounted(() => {
                // 将showDetails方法暴露给grid组件
                if (grid.value && grid.value.$refs && grid.value.$refs.table) {
                    grid.value.$refs.table.showDetails = showDetails;
                }
                
                console.log('ProductionWorkOrder组件已挂载');
            });

            const table = ref({
                key: 'ProductionWorkOrderId',
                footer: "Foots",
                cnName: '生产工单',
                name: '/productmanage/productmanage/ProductionWorkOrder',
                url: "/ProductionWorkOrder/",
                sortName: "CreateDate",
                rowClick: (row) => {
                    showDetails(row);
                }
            });
            const editFormFields = ref({"ProductionWorkOrderCode":"","WorkOrderStatus":[],"WorkOrderPriority":false,"WorkshopId":"","ProcessmanagementId":[]});
            const editFormOptions = ref([[{"title":"工单编号","field":"ProductionWorkOrderCode","type":"text","placeholder":"请输入，忽略将自动生成"},
                               {"title":"工单状态","required":true,"field":"WorkOrderStatus","type":"select","dataKey":"workOrderStatus","data":[]}],
                              [{"title":"工单优先级","field":"WorkOrderPriority","type":"radio","dataKey":"WorkOrderPriority","data":[]}],
                              [{"title":"车间","field":"WorkshopId","type":"select","dataKey":"Workshop","data":[]},
                               {"title":"工艺路线","field":"ProcessmanagementId","type":"select","dataKey":"Processmanagement","data":[]}]]);
            const searchFormFields = ref({"ProductionWorkOrderCode":"","WorkOrderStatus":[]});
            const searchFormOptions = ref([[{"title":"工单编号","field":"ProductionWorkOrderCode","type":"like"},{"title":"工单状态","field":"WorkOrderStatus","type":"select"}]]);
            const columns = ref([{field:'ProductionWorkOrderId',title:'生产工单主键',type:'guid',width:110,hidden:true,readonly:true,require:true,align:'left'},
                       {field:'ProductionWorkOrderCode',title:'工单编号',type:'string',width:180,align:'left',sort:true},
                       {field:'WorkOrderStatus',title:'工单状态',type:'int',sort:true,width:180,require:true,align:'left',bind:{ key:'workOrderStatus',data:[]}},
                       {field:'WorkOrderPriority',title:'工单优先级',type:'int',width:220,align:'left'},
                       {field:'WorkshopId',title:'车间',type:'datetime',sort:true,width:110,align:'left',sort:true,bind:{ key:'Workshop',data:[]}},
                       {field:'ProcessmanagementId',title:'工艺路线',type:'int',width:80,hidden:true,align:'left',bind:{ key:'Processmanagement',data:[]}},
                       {field:'Creator',title:'创建人',type:'string',width:130,align:'left'},
                       {field:'CreateDate',title:'创建时间',type:'datetime',width:110,align:'left',sort:true}
                    ]);
             const detail = ref({
                cnName: "工单计划信息",
                table: "ProductWorkOrderList",
                columns: [
                    // {field:'WorkOrderPlanningId',title:'工单计划明细主键',type:'guid',width:110,hidden:true,readonly:true,require:true,align:'left', isSubmit: true },
                    {field:'ProductionWorkOrderId',title:'生产工单主键',hidden:true,type:'guid',sort:true,width:110,require:true,align:'left',sort:true},
                    {field:'ProductionPlanningId',title:'生产计划主键',type:'guid',sort:true,width:180,edit:{type:'text'},require:true,align:'left'},
                    {field:'ProductionPlanningCode',title:'生产计划编号',type:'string',sort:true,width:180,edit:{type:'text'},require:true,align:'left'},
                    {field:'ReportworkNum',title:'报工数量',type:'string',sort:true,width:110,align:'left',sort:true},
                    {field:'ProductId',title:'成品主键',type:'int',width:80,hidden:true,align:'left'},
                    {field:'ProductionOrderId',title:'生产订单主键',type:'int',width:130,align:'left'},
                    {field:'PlanningStartDate',title:'计划开始日期',type:'string',width:130,align:'left'},
                    {field:'PlanningEndDate',title:'计划结束日期',type:'guid',width:130,align:'left'},
                    {field:'ActualStartDate',title:'实际开始日期',type:'string',width:130,align:'left'},
                    {field: 'ActualEndDate', title: '实际结束日期',type: 'string', sort: true, width: 250, align: 'left', sort: true },
                    {field: 'CurrentPlanNum', title: '本次计划数量',type: 'string', sort: true, width: 250, align: 'left', sort: true }
                ],
                sortName: "WorkOrderPlanningId",
                key: "WorkOrderPlanningId"
            });
            
            // 添加辅助方法
            const getProductUnitText = (unitId) => {
              const stateMap = {
                1: '个',
                2: '箱',
                3: '件',
                4: '套',
                5: '台',
                6: '米',
                7: '条',
              };
              return stateMap[unitId] || '未知单位';
            };

            const getProductStateText = (stateId) => {
              const stateMap = {
                1: '启用',
                2: '禁用',
              };
              return stateMap[stateId] || '未知状态';
            };
            
            return {
                table,
                extend,
                editFormFields,
                editFormOptions,
                searchFormFields,
                searchFormOptions,
                columns,
                detail,
                showDetails,
                detailsDialogVisible,
                backupDialogVisible,
                currentDetailRow,
                grid,
                getProductUnitText,
                getProductStateText,
            };
        },
    });
</script>

<style scoped>
.detail-card {
  margin-bottom: 20px;
  border-radius: 4px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}
</style>
